<script setup lang="ts">
import { PlusOutlined } from '@ant-design/icons-vue'
import { notification } from 'ant-design-vue'
import { defineComponent, ref } from 'vue'
import type { ProductModel } from '@/api/product/product-list.ts'
import { createProductInfo, getProductListAll } from '@/api/product/product-list.ts'

// 添加一个方法来触发自定义事件，传递地址信息给父组件
const emit = defineEmits(['productSelected'])

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render() {
    return this.vnodes
  },
})

let index = 0
const items = ref(['jack', 'lucy'])
const productId = ref()
const inputRef = ref()
const name = ref()
const formModel = reactive<ProductModel>({})
// 创建产品信息
async function addItem() {
  // e.preventDefault()
  formModel.productName = name.value
  const res = await createProductInfo({
    ...formModel,
  })
  if (res.code === 200) {
    items.value.push(formModel.productName)
    name.value = ''
    notification.success({
      message: '添加成功',
      duration: 3,
    })
  }
  else {
    notification.error({
      message: res.msg,
      duration: 3,
    })
  }
  console.log('addItem')
  init()
  setTimeout(() => {
    inputRef.value?.focus()
  }, 0)
}
function productSelected() {
  console.log(`productSelected${productId.value}`)

  emit('productSelected', productId.value)
}


const productModelMap = shallowRef<ProductModel[]>([])
async function init() {
  console.log('进入到初始产品列表函数中')
  // 初始加载所有产品
  const { data } = await getProductListAll()
  console.log('已获取到产品列表')
  console.log(data)
  productModelMap.value = data ?? []
}

onMounted(() => {
  init()
})
</script>

<template>
  <a-select v-model:value="productId" placeholder="请选择采购产品" style="width: 300px" @change="productSelected">
    <a-select-option v-for="productModel in productModelMap" :value="productModel.productId">
      {{ productModel.productName }}
    </a-select-option>
    <template #dropdownRender="{ menuNode: menu }">
      <v-nodes :vnodes="menu" />
      <a-divider style="margin: 4px 0" />
      <a-space style="padding: 4px 8px">
        <a-input ref="inputRef" v-model:value="name" placeholder="请输入产品名称" />
        <a-button type="text" @click="addItem">
          <template #icon>
            <plus-outlined />
          </template>
          添加产品
        </a-button>
      </a-space>
    </template>
  </a-select>
</template>

<style scoped lang="less">

</style>
